package 数组.合并区间56;

import utils.Utils;

import java.util.*;

public class Solution {

    public static int[][] merge(int[][] intervals) {
        if(intervals.length < 1){
            return null;
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> list = new ArrayList<>();

        for(int i=0;i<intervals.length;i++){
            int l = intervals[i][0];
            int r = intervals[i][1];
            // 如果当前左边界大于上一个的右边界，说明
            // 当前的一定是新数组
            if(list.size() == 0 || list.get(list.size() - 1)[1] < l){
                list.add(new int[]{l,r});
            }else{
                list.get(list.size() - 1)[1] = Math.max(list.get(list.size() - 1)[1],r);
            }
        }

        return list.toArray(new int[0][0]);

    }

    public static void main(String[] args) {
        int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
        Utils.printIntArrArr(merge(intervals));
    }
}
